import {ref} from "vue";
import {useRouter} from "vue-router";
import useUserStore from "@/stores/admin/useUserStore";
import {lodashFunc} from "@/utils/soul";
import {getCodeImg} from "@/api/system/loginApi";
import Cookies from "js-cookie";
import {decrypt, encrypt} from "@/utils/encryptUtil";

export default () =>{
    const loginFormRef = ref();
    const codeUrl = ref("");
    const loginForm = ref({
        username: "",
        password: "",
        rememberMe: false,
        code: "",
        uuid: "",
    });

    const loginRules = {
        username: [
            { required: true, trigger: "blur", message: "用户名不能为空" },
        ],
        password: [
            { required: true, trigger: "blur", message: "密码不能为空" },
        ],
        code: [
            { required: true, trigger: "change", message: "验证码不能为空" },
        ],
    };

    const loading = ref(false);
    const redirect = ref(undefined);

    const router = useRouter();

    const getCodeBase64 = () => {
        getCodeImg().then((res) => {
            if (res.status === 200) {
                const data = res.data;
                loginForm.value.uuid = data.uuid;
                const captchaImg = data.captchaImg;
                if (captchaImg.indexOf("data:image") > -1) {
                    codeUrl.value = captchaImg;
                } else {
                    codeUrl.value = "data:image/png;base64," + captchaImg;
                }
            }
        });
    };

    // 验证码防抖，设置每700毫秒才能点击一次
    const getCode = lodashFunc(getCodeBase64, 700);

    const getCookie = () => {
        const username = Cookies.get("username");
        const password = Cookies.get("password");
        const rememberMe = Cookies.get("rememberMe");

        loginForm.value.username = username === undefined ? loginForm.value.username : username;

        loginForm.value.password = password === undefined ? loginForm.value.password : decrypt(password);

        loginForm.value.rememberMe = rememberMe === undefined ? false : Boolean(rememberMe);
    };

    /**
     * 登录方法
     */
    const handleLogin = (callback) => {
        loginFormRef.value?.validate((valid) => {
            if (!valid) {
                loading.value = true;
                if (loginForm.value.rememberMe) {
                    // prettier-ignore
                    Cookies.set("username", loginForm.value.username, { expires: 30,});
                    // prettier-ignore
                    Cookies.set("password", encrypt(loginForm.value.password).toString(), {expires: 30, });
                    // prettier-ignore
                    Cookies.set("rememberMe", loginForm.value.rememberMe.toString(), { expires: 30, });
                } else {
                    Cookies.remove("username");
                    Cookies.remove("password");
                    Cookies.remove("rememberMe");
                }
                useUserStore().login(loginForm.value)
                    .then(() => {
                        if (callback && typeof callback == 'function'){
                            useUserStore().getInfo().then(res=>{
                                callback(() => {loading.value = false;});
                            })
                        }else {
                            router.push({ path: "/admin/home" }).catch(() => {loading.value = false;});
                        }
                    })
                    .catch(() => {
                        loading.value = false;
                        getCode();
                    });
            }
        });
    };

    getCode();
    getCookie();
    return {
        loginFormRef, loginForm, loginRules, codeUrl, loading, getCode, handleLogin,
    };
}
